package com.example.testhttp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;

public class HttpUtils {
	public static String get(String urlString, String key) {
		try {
			String encrypt = DesUtils.encrypt("?" + key);
			URL url = new URL(urlString + encrypt);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			if (code == 200) {
				InputStream is = conn.getInputStream();
				return DesUtils.decrypt(toString(is));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "-1";
	}

	private static String toString(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = is.read(buffer)) != -1) {
			baos.write(buffer, 0, len);
		}
		is.close();
		byte[] result = baos.toByteArray();
		return new String(result);
	}

	public static String getDeviceId(Context context) {

		StringBuilder deviceId = new StringBuilder();
		// 渠道标志
		deviceId.append("a");
		try {
			// wifi mac地址
			WifiManager wifi = (WifiManager) context
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo info = wifi.getConnectionInfo();
			String wifiMac = info.getMacAddress();
			if (!isEmpty(wifiMac)) {
				deviceId.append("wifi");
				deviceId.append(wifiMac);
				return deviceId.toString();
			}

			// IMEI
			TelephonyManager tm = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			String imei = tm.getDeviceId();
			if (!isEmpty(imei)) {
				deviceId.append("imei");
				deviceId.append(imei);
				return deviceId.toString();
			}

			// 序列号
			String sn = tm.getSimSerialNumber();
			if (!isEmpty(sn)) {
				deviceId.append("sn");
				deviceId.append(sn);
				return deviceId.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}

	private static String urlString;

	public static boolean validate(Context context) {
		String deviceId = getDeviceId(context);
		if (!isEmpty(deviceId)) {
			String string = get(urlString, deviceId);
			if (!isEmpty(string) && "1".equals(string)) {
				return true;
			}
		}
		return false;
	}

	private static boolean isEmpty(String wifiMac) {
		if (wifiMac == null) {
			return true;
		}
		if (wifiMac.trim().equals("")) {
			return true;
		}
		return false;
	}

}
